<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DT测试</title>
<script src="jQuery-2.1.4.min.js"></script>
<script src="jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.dataTables.min.css">
</head>
<body>

<button name="btn1" id="rebulidTable" onclick="btnTable()" class="btn btn-flat" style="width:100px;height:50px">按钮1</button>

<div id="app">
<table id="example" class="display" style="width:100%"></table>
</div>

<button onclick="btnTable2()" class="btn btn-flat" style="width:100px;height:50px">按钮2</button>

<div>
<table id="example2" class="display" style="width:100%"></table>
</div>

<script>

$(function(){ 
    btnTable();
    btnTable2();
}) 

//var table;
var hash_table={};
var flag=0;
var result = {
    "data":
    [
        {
            "position": "老板",
            "age": 19,
            "name": "小明",
            "sex": "男"
        },
        {
            "position": "职工",
            "age": 20,
            "name": "小红",
            "sex": "女"
        }
    ],
    "cols": 
    [
        ["name", "名字"],
        ["position", "职位"],
        ["sex", "性别"],
        ["age", "年龄"]
    ]
}


var result2 = {
    "data":
    [
        ["小明", "男",100],
        ["小红","女",90],
    ],
    "cols": 
    [
        ["name", "名字"],
        ["sex", "性别"],
        ["score", "分数"]
    ]
}

function btnTable()
{   
    var columnArray=[];
    for(var i=0;i<result.cols.length;i++)
    {
        var json={data:null,title:null}
        json.data=result.cols[i][0];
        json.title=result.cols[i][1];
        columnArray.push(json);
    }
    if(flag==0)
    {
        flag=1;
        aitem=columnArray.pop();
    }
    else
        flag=0;
    if(hash_table['example']!=undefined)
    {
        hash_table['example'].destroy();
        $("#example").empty();
    }
    initTable(result.data,columnArray);
}

function btnTable2()
{   
    var columnArray=[];
    for(var i=0;i<result2.cols.length;i++)
    {
        var json={title:null}
        json.title=result2.cols[i][1];
        columnArray.push(json);
    }
    if(flag==0)
    {
        flag=1;
        aitem=columnArray.pop();
    }
    else
        flag=0; 

    initTablePro('example2',result2.data,columnArray);
}

function initTable(mydata,mycol)
{
    console.log(mydata)
    hash_table['example']=$('#example').DataTable( {
        "data":mydata,
        "columns":mycol,
    });
}

function initTablePro(dom_id,mydata,mycol)
{
    if(hash_table[dom_id]!=undefined)
    {
        hash_table[dom_id].destroy();
        $("#"+dom_id).empty();
    }
    console.log(mydata)
    var options={
        "data":mydata,
        "columns":mycol,
    }
    hash_table[dom_id]=$('#'+dom_id).DataTable(options);
}

</script>
</body>
</html>